package com.tarena.lbs.coupon.service.impl;

import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.coupon.dao.repository.CouponRepository;
import com.tarena.lbs.coupon.pojo.param.CouponParam;
import com.tarena.lbs.coupon.pojo.po.CouponPO;
import com.tarena.lbs.coupon.pojo.query.CouponQuery;
import com.tarena.lbs.coupon.pojo.vo.CouponVO;
import com.tarena.lbs.coupon.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CouponServiceImpl implements CouponService {
    @Autowired
    private CouponRepository couponRepository;
    @Override
    public void save(CouponParam couponParam) {
        log.info("保存优惠券业务:{}"+couponParam);
        CouponPO couponPO = new CouponPO();
        BeanUtils.copyProperties(couponParam, couponPO);
        couponPO.setBusinessId(1);
        couponPO.setCreateAt(new Date());
        couponPO.setUpdateAt(new Date());
        // 确保必填字段有值
        if (couponPO.getStartDate() == null) {
            couponPO.setStartDate(new Date()); // 设置默认开始时间为当前时间
        }
        // 如果没有设置结束时间，默认设置为开始时间后30天
        if (couponPO.getEndDate() == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(couponPO.getStartDate());
            calendar.add(Calendar.DAY_OF_MONTH, 30); // 默认30天有效期
            couponPO.setEndDate(calendar.getTime());
        }
        couponPO.setStatus(1);
        couponPO.setEnableStatus(1);
        couponRepository.save(couponPO);
        log.info("保存优惠券成功");
    }

    @Override
    public CouponVO detail(Integer id) {
        CouponPO couponPO= couponRepository.detail(id);
        if(couponPO != null){
            CouponVO couponVO = new CouponVO();
            BeanUtils.copyProperties(couponPO, couponVO);
            return couponVO;
        }else{
            log.info("优惠券不存在");
            return null;
        }
    }

    @Override
    public List<CouponVO> pageList(CouponQuery couponQuery) {
        List<CouponVO> pageResult = couponRepository.pageList(couponQuery);
        log.debug("分页查询优惠券数据，入参:{}", couponQuery);
        log.info("分页查询优惠券数据，出参:{}", pageResult);
        return pageResult;
    }

    @Override
    public void delete(Integer id) {
        log.debug("删除优惠券业务:{}", id);
        couponRepository.delete(id);
    }


}